import { defineComponent, nextTick, PropType, reactive, ref, watch } from 'vue'
import MsTable from '@/components/Tables'
import DictChildrenForm from './Form'
import { deleteDict } from '@/api/sys/dictChildren'
import { message } from 'ant-design-vue'
import useTable from '@/hooks/useTable'

export interface IDictChildrenType {
  id?: string;
  dictValue?: string;
  code?: string;
  bookType?: string;
  dictOrder?: number;
}

export default defineComponent({
  name: 'Dict',
  props: {
    dictType: {
      type: String as PropType<string>,
      default: ''
    }
  },
  setup(props) {
    const { msTable, searchTable, tableData: state } = useTable()
    const tableConf = {
      columns: [
        { dataIndex: 'dictValue', title: '字典值' },
        { dataIndex: 'code', title: '对应码' },
        { title: '操作', slots: { customRender: 'action' } }
      ]
    }

    const handleDelDict = (id: string) => {
      deleteDict(id).then((res) => {
        if (res.state) {
          message.success(res.msg)
          searchTable()
        }
      })
    }

    watch(() => props.dictType, (val) => {
      nextTick(() => {
        (state.searchForm as any).dictType = val
        searchTable()
      })
    })

    const tableSolts = {
      action: ({ record }: { record: IDictChildrenType }) => (
        <>
          <a onClick={() => { (state.currentId as string | undefined) = record.id; state.dialogVisible = true }}>修改</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" ok-text="是" cancel-text="否" onConfirm={() => handleDelDict(record.id as string)}>
            <a>删除</a>
          </a-popconfirm>
        </>
      )
    }

    return () => {
      return (
        <a-card title="字典关联表" bordered={false}>
          {
            props.dictType ? (
              <>
                <a-button type="primary" onClick={() => { state.currentId = ''; state.dialogVisible = true }}>添加</a-button>
                <MsTable
                  v-slots={tableSolts}
                  searchForm={state.searchForm}
                  ref={msTable}
                  columns={tableConf.columns}
                  api="/sys/dict/list"
                  rowKey="dictValue"
                />
              </>
            ) : (<a-empty description="请选择配置字典类型" />)
          }
          <DictChildrenForm dictType={props.dictType} v-model={[state.dialogVisible, 'visible']} formId={state.currentId} />
        </a-card>
      )
    }
  }
})
